#pragma once
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>
#define BUFFER_SIZE 1024

class InetAddr
{
public:
    // 默认构造函数
    InetAddr() : _port(0), _len(sizeof(_addr))
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
    }

    // 从sockaddr_in构造
    InetAddr(const struct sockaddr_in &addr)
        : _addr(addr), _len(sizeof(_addr))
    {
        char buffer[BUFFER_SIZE];
        _ip = inet_ntop(AF_INET, &addr.sin_addr, buffer, sizeof(buffer));
        _port = ntohs(_addr.sin_port); // 网络字节序转主机字节序
    }

    // 从IP字符串和端口构造
    InetAddr(const std::string &ip, in_port_t port)
        : _ip(ip), _port(port), _len(sizeof(_addr))
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        inet_pton(AF_INET, ip.c_str(), &_addr.sin_addr);
        _addr.sin_port = htons(port); 
    }

    // 从网络字节序IP和端口构造（用于INADDR_ANY）
    InetAddr(in_addr_t ip, in_port_t port)
        : _port(port), _len(sizeof(_addr))
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_addr.s_addr = ip;
        _addr.sin_port = htons(port);

        // 转换为IP字符串
        char buffer[BUFFER_SIZE];
        _ip = inet_ntop(AF_INET, &_addr.sin_addr, buffer, sizeof(buffer));
    }

    bool operator==(const InetAddr &addr) const
    {
        return (_ip == addr._ip && _port == addr._port);
    }

    std::string &Ip() { return _ip; }
    const std::string &Ip() const { return _ip; }

    in_port_t &Port() { return _port; }
    const in_port_t &Port() const { return _port; }

    struct sockaddr_in &NetAddr() { return _addr; }
    const struct sockaddr_in &NetAddr() const { return _addr; }

    struct sockaddr *NetAddrPtr() { return (struct sockaddr *)&_addr; }
    const struct sockaddr *NetAddrPtr() const { return (struct sockaddr *)&_addr; }

    std::string Info() const { return _ip + ":" + std::to_string(_port); }
    socklen_t &AddrLen() { return _len; }
    const socklen_t &AddrLen() const { return _len; }

private:
    std::string _ip;
    in_port_t _port;          // 主机字节序的端口
    struct sockaddr_in _addr; // 网络字节序的地址结构
    socklen_t _len;
};